package controleur;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.dom.NodeList;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
        
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathException;
import javax.xml.xpath.XPathExpressionException;
import persistence.DB;
import org.xml.sax.SAXException;

/**
 *
 * @author Nishruu
 */
@WebServlet(name="NewServlet", urlPatterns={"/NewServlet"})
public class MainServlet extends HttpServlet {

    private List<String[]> listeSemaines;
    private List<String[]> listeVilles;
    private DB bd;
    


    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//        response.setContentType("text/html;charset=UTF-8");
//        String action = request.getParameter("action");
//        try {
//
//
//             if (action.equals("getPopularite")) {
//
//                String nomgroupe = request.getParameter("nomgroupe");
//                List<String> listegroupes = new ArrayList<String>();
//
//                String sql = "SELECT * FROM GROUPE";
//                ResultSet rs = bd.read(sql);
//                while(rs.next()) listegroupes.add(rs.getString(1));
//                request.setAttribute("listeGroupes",listegroupes);
//
//
//                if (nomgroupe != null) {
//                    String id_semaine = listeSemaines.get(listeSemaines.size()-1)[0];
//
//                    List<String> listevillesOK = new ArrayList<String>();
//                    List<Integer> popularite = new ArrayList<Integer>();
//                    List<String[]> listeCoords = new ArrayList<String[]>(2);
//
//                    sql = "SELECT * FROM POPULARITE WHERE id_groupe = "
//                            + "\'" + nomgroupe + "\'"
//                            + " AND id_semaine = \'" + id_semaine + "\'"
//                            + " LIMIT 1";
//
//                    rs = bd.read(sql);
//
//                    if (rs.next() == false) {
//
//                        String urlspecif = url + "geo.getmetroartistchart&country=" + api_key;
//                        Object result = null;
//                        String ville = null;
//                        String pays = null;
//
//                        for(int i=103; i < listeVilles.size(); ++i) {
//                            ville = listeVilles.get(i)[0];
//                            pays = listeVilles.get(i)[1];
//
//                            System.out.println(urlspecif + "&country=" + pays + "&metro=" + ville + "&limit=500");
//                            result = parse(urlspecif + "&country=" + pays + "&metro=" + ville + "&limit=500","string(//artist[./name='" + nomgroupe + "']/@rank)");
//                            if (result != null && (String)result != "") {
//
//                                sql = "INSERT INTO POPULARITE(nom_ville,nom_pays,id_semaine,id_groupe,popularite) "
//                                        + "VALUES(\'" + ville + "\',"
//                                        + "\'" + pays + "\',"
//                                        + "\'" + id_semaine + "\',"
//                                        + "\'" + nomgroupe + "\',"
//                                        + "\'" + Integer.parseInt((String) result) + "\')";
//
//                                System.err.println(sql);
//                                bd.write(sql);
//                                //if(rs.next()) return new Utilisateur(login,password,rs.getString("chefdelabo"));
//                                //else return null;
//                            }
//                        }
//                     }
//
//                    sql = "SELECT P.nom_ville, V.latitude, V.longitude, popularite"
//                            + " FROM POPULARITE P,VILLE V"
//                            + " WHERE P.id_semaine =\'" + id_semaine + "\'"
//                            + " AND P.id_groupe =\'" + nomgroupe + "\'"
//                            + " AND V.nom_ville = P.nom_ville"
//                            + " ORDER BY 4 DESC";
//
//                    System.err.println(sql);
//                    rs = bd.read(sql);
//
//                    int compteur = 1;
//                    while(rs.next()){
//                        popularite.add(compteur++);
//                        listevillesOK.add(rs.getString("nom_ville"));
//                        String[] coords = new String[2];
//                        coords[0] = rs.getString("latitude");
//                        coords[1] = rs.getString("longitude");
//                        listeCoords.add(coords);
//                    }
//
//
//                    //String[] s;
//                    //if(request.getParameter("debut") == null && request.getParameter("fin") == null) {
//                    //s = listeSemaines.get(listeSemaines.size() - 1);
//                    /*}
//                    /else {
//                        s = new String[2];
//                        s[0] = request.getParameter("debut");
//                        s[1] = request.getParameter("fin");
//                    }*/
//
//                    //result = parse(urlspecif + "&start=" + s[0] + "&end=" + s[1] + "&limit=500","string(//artist[./name='" + nomgroupe + "']/@rank)");
//                    request.setAttribute("popularite", popularite);
//                    request.setAttribute("listevillesOK", listevillesOK);
//                    request.setAttribute("listeCoords",listeCoords);
//                    request.setAttribute("nomgroupe"," du groupe : " + nomgroupe + " ");
//                }
//                else request.setAttribute("nomgroupe"," d'un groupe ");
//
//                RequestDispatcher dispatch = request.getRequestDispatcher("maps.jsp");
//                dispatch.forward(request, response);
//            }
//
//
//            if (action.equals("getSemaines")) {
//
//                List<String[]> semaines = getSemaines();
//                //rajouté pour que la réponse soit affichée dans stats.jsp
//                request.setAttribute("semaines",semaines);
//                //RequestDispatcher dispatch = request.getRequestDispatcher("stats.jsp");
//                //dispatch.forward(request, response);
//            }
//
//            if (action.equals("getGroupes")) {
//                List<String> listeartistes = new ArrayList<String>();
//                Object result = parse(url + "user.gettopartists&user=nishruu" + api_key, "//artist/name/text()");
//                NodeList nodes = (NodeList) result;
//                for (int i = 0; i < nodes.getLength(); i++) {
//                    listeartistes.add(nodes.item(i).getNodeValue());
//                }
//                request.setAttribute("listeartistes", listeartistes);
//            }
//
//            else if (action.equals("getVilles")) {
//
//                request.setAttribute("listevilles",  getVilles());
//                //rajouté pour que la réponse soit affichée dans maps.jsp
//                //RequestDispatcher dispatch = request.getRequestDispatcher("maps.jsp");
//                //dispatch.forward(request, response);
//
//            }
//        }
//
//        catch (SQLException ex) {
//            Logger.getLogger(MainServlet.class.getName()).log(Level.SEVERE, null, ex);
//        }
//        catch (ParserConfigurationException ex) {
//            Logger.getLogger(MainServlet.class.getName()).log(Level.SEVERE, null, ex);
//        }
//        catch (XPathExpressionException ex) {
//            Logger.getLogger(MainServlet.class.getName()).log(Level.SEVERE, null, ex);
//        }
//
//        RequestDispatcher dispatch = request.getRequestDispatcher("index.jsp");
//        dispatch.forward(request, response);
    }

   
    
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
